package de.zainodis.triplog.ui.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import de.zainodis.triplog.R;
import de.zainodis.triplog.ui.task.SaveNoteService;

/**
 * Created by fzarrai on 10/7/2014.
 */
public class EditNoteFragment extends Fragment {

    private static final String BUNDLE_TEXT = "BundleText";

    public EditNoteFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Editable editable = getEditText().getText();
        String text = editable != null ? editable.toString() : "";
        outState.putString(BUNDLE_TEXT, text);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (savedInstanceState != null && savedInstanceState.containsKey(BUNDLE_TEXT)) {
            //Restore text after config change
            getEditText().setText(savedInstanceState.getString(BUNDLE_TEXT));
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_edit_note, container, false);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.edit_note, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_done) {
            String text = getText();
            Activity parent = getActivity();
            if (parent != null && !parent.isFinishing()) {
                Intent intent = new Intent(parent, SaveNoteService.class);
                intent.putExtra(SaveNoteService.BUNDLE_TEXT, text);
                parent.startService(intent);
                parent.onBackPressed();
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private String getText() {
        Editable editable = getEditText().getText();
        String text = editable != null ? editable.toString() : null;
        return text;
    }

    private EditText getEditText() {
        return (EditText) getView().findViewById(R.id.fragment_edit_note_text);
    }
}
